<template>
	<div class="course">
		<!-- 筛选条件区域 -->
		<div class="filter-container" style="border-bottom: 1px dashed #dddddd;" @click="clearRouteParams">
			<!-- 学段筛选 -->
			<div class="filter-item">
				<span class="filter-label font14">学段：</span>
				<el-checkbox-group
					@change="handleStageChange"
					class="filter-options font14"
					v-model="queryParams.stages"
				>
					<el-checkbox-button
						v-for="item in stageOptions"
						:key="item.key"
						:label="item.key"
					>
						{{ item.value }}
					</el-checkbox-button>
				</el-checkbox-group>
			</div>

			<div class="filter-item">
				<span class="filter-label font14">年级：</span>
				<el-checkbox-group
					@change="queryCourseList"
					class="filter-options font14"
					v-model="queryParams.grades"
				>
					<el-checkbox-button
						v-for="item in gradeOptions"
						:key="item.key"
						:label="item.key"
					>
						{{ item.value }}
					</el-checkbox-button>
				</el-checkbox-group>
			</div>

			<div class="filter-item">
				<span class="filter-label font14">学科：</span>
				<el-checkbox-group
					@change="queryCourseList"
					class="filter-options font14"
					v-model="queryParams.series"
				>
					<el-checkbox-button
						v-for="item in seriesOptions"
						:key="item.subject"
						:label="item.subject"
					>
						{{ item.subject }}
					</el-checkbox-button>
				</el-checkbox-group>
			</div>

			<div class="filter-item">
				<span class="filter-label font14">版本：</span>
				<el-select style="width: 500px;float: left" multiple v-model="queryParams.seriesNos">
					<el-option v-for="item in versionOptions" :label="item.value" :value="item.key"></el-option>
				</el-select>
			</div>

			<!-- 册次筛选（单选，保持不变） -->
			<div class="filter-item">
				<span class="filter-label font14">册次：</span>
				<el-checkbox-group @change="queryCourseList" class="filter-options font14" v-model="queryParams.semesters">
					<el-checkbox-button
						v-for="item in volumeOptions"
						:key="item.key"
						:label="item.key"
					>
						{{ item.value }}
					</el-checkbox-button>
				</el-checkbox-group>
			</div>

			<!-- 类型筛选（单选，保持不变） -->
			<div class="filter-item">
				<span class="filter-label font14">类型：</span>
				<el-radio-group @change="queryCourseList" class="filter-options font14" v-model="typeValue">
					<el-radio-button
						v-for="item in typeOptions"
						:key="item.key"
						:label="item.key"
					>
						{{ item.value }}
					</el-radio-button>
				</el-radio-group>
			</div>
		</div>

		<template v-for="(item, index) in bookList" :key="index">
			<!-- 只渲染有章节数据的项 -->
			<div
				class="course-content"
				v-if="item.chapterTrees.length > 0"
			>
				<aside class="sidebar">
					<div class="book-info" @click="bookDetail(item)">
						<div class="book-text">
							<p>{{ item.name }}</p>
						</div>
					</div>
					<div class="chapter-list">
						<tree
							:data="item.chapterTrees"
							:courseNo="item.courseNo"
							tab="course"
							:expandAll="expandAll"
							:maxLevel="3"
							:btn="false"
						/>
					</div>
				</aside>

			</div>
		</template>
	</div>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref, watch } from 'vue';
import tree from '/#/tree/index.vue';
import {
	getSemesterCombobox,
	getStageCombobox,
	getComboboxByStageId,
	getSeriesTree
} from '/@/api/home';
import {
	searchCourse,
	getCourseByNO,
	getSeriesComboboxByStage
} from '/@/api/course';

import {
	getKnowledgePointsById
} from '/@/api/knowledge';
import { useCool } from '/@/cool/hooks';
import { useRoute, useRouter } from 'vue-router';


// 路由与路由参数
const route = useRoute();
const { router } = useCool();
let expandAll = ref(false);
// 筛选参数（多选字段均初始化为数组）
const queryParams = reactive({
	grades: [] as string[],       // 年级（多选）
	pageNum: 1,
	pageSize: 10,
	total: 0,
	semesters: [] as string[],               // 册次（单选）
	seriesNos: [] as string[],  // 版本（多选）
	stages: [] as string[],      // 学段（多选）
	series: [] as string[],     // 学科（多选）
	sortType: 'smart'           // 排序类型（新增）
});

let courseNoStrs = ref([]);
// 选项数据
const stageOptions = ref([]);       // 学段选项
const gradeOptions = ref([]);       // 年级选项
const volumeOptions = ref([]);      // 册次选项
const versionOptions = ref([]);     // 版本选项
const seriesOptions = ref([]);      // 学科选项
const typeOptions = ref([{ value: '同步课', key: '1' }]);  // 类型选项
const typeValue = ref('1');         // 类型选中值（单选）
const bookList = ref([]);           // 课程列表

const handleStageChange = async () => {
	queryParams.grades = [];
	queryParams.seriesNos = [];
	await queryCourseList();  // 触发查询
};

// 版本变化事件（修复互斥逻辑）
const handleVersionChange = async (selected: string[]) => {
	// 选中"通用版"（key=200）时，强制只保留该选项
	if (selected.includes('200')) {
		queryParams.seriesNos = ['200'];
	}
	await queryCourseList();
};
const resetForm = () => {
	queryParams.semesters = [];
	queryParams.seriesNos = [];
	queryParams.grades = [];
	queryParams.stages = [];
	queryParams.series = [];
}

// 查询课程列表
const queryCourseList = async () => {
	const res = await searchCourse(queryParams);
	if (route.query.id) {
		let list = [] as any;
		courseNoStrs.value.forEach((item, index) => {
			let arr = item.split(',');
			arr.forEach(child => {
				list.push(Number(child));
			})
		});
		res.data.list.forEach((item) => {
			item.chapterTrees = filterTreeByCourseNoStrs(item.chapterTrees,list)
		});
		expandAll.value = true;
	} else {
		expandAll.value = false;
	}
	bookList.value = res.data.list;
	queryParams.total = res.data.total;
};

// 课程详情跳转
const bookDetail = async (item: any) => {
	await router.push({
		path: '/course/detail',
		query: { ...item, type: 'edit' }
	});
};

const filterTreeByCourseNoStrs = (nodes: any[], targetChapterNos: number[]): any[] => {
	return nodes.reduce((filtered, node) => {
		// 递归过滤子节点
		const filteredChildren = node.children
			? filterTreeByCourseNoStrs(node.children, targetChapterNos)
			: [];
		// 节点自身是否符合条件（chapterNo 在目标数组中）
		const isNodeMatch = targetChapterNos.includes(node.chapterNo);
		// 子节点是否有符合条件的（确保父节点被保留）
		const hasMatchedChildren = filteredChildren.length > 0;

		// 如果自身匹配或有匹配的子节点，则保留该节点（并使用过滤后的子节点）
		if (isNodeMatch || hasMatchedChildren) {
			filtered.push({
				...node,
				children: filteredChildren // 子节点已过滤
			});
		}

		return filtered;
	}, [] as any[]);
};
// 初始化数据
const initData = async () => {
	// 获取学段选项
	const stageRes = await getStageCombobox();
	stageOptions.value = stageRes.data;

	// 初始选中第一个学段（修复：赋值为数组）
	if (stageOptions.value.length > 0) {
		queryParams.stages = [stageOptions.value[1].key];
	}
};

// 监听学段变化，加载依赖选项
watch(
	() => queryParams.stages,
	async (newVal) => {
		// 学段未选中时不执行
		if (!newVal || newVal.length === 0) return;
		const configs = [
			{
				api: getComboboxByStageId,
				optionsRef: gradeOptions,
				paramKey: 'grades',
				valueKey: 'key'
			},
			{
				api: getSeriesComboboxByStage,
				optionsRef: versionOptions,
				paramKey: 'seriesNos',
				valueKey: 'key'
			},
			{
				api: getSemesterCombobox,
				optionsRef: volumeOptions,
				paramKey: 'semesters',
				valueKey: 'key'
			},
			{
				api: getSeriesTree,
				optionsRef: seriesOptions,
				paramKey: 'series',
				valueKey: 'subject'
			}
		];

		// 循环处理每个配置项
		for (const config of configs) {
			// 调用对应的API获取数据
			const res = await config.api(newVal);
			config.optionsRef.value = res.data;

			// 设置默认选中值
			if (config.optionsRef.value.length > 0 && !route.query.id) {
				//const value = config.paramKey=='grades'?config.optionsRef.value[1][config.valueKey]:config.optionsRef.value[0][config.valueKey];
				let value = null;
				if (config.paramKey=='grades') {
					value = config.optionsRef.value[1][config.valueKey];
				}
				else {
					value = config.optionsRef.value[0][config.valueKey];
				}
				// 处理数组和非数组的情况
				queryParams[config.paramKey] = Array.isArray(queryParams[config.paramKey])
					? [value]
					: value;
			}
		}

		// 触发查询
		await queryCourseList();
	},
	{ immediate: true }
);
const routerInstance = useRouter();
const clearRouteParams = () => {
	if (Object.keys(route.query).length > 0) {
		routerInstance.replace({
			path: route.path,
			query: {}
		});
	}
};
onMounted(async () => {
	await initData();

	// 从路由参数加载课程详情
	if (route.query.id) {
		resetForm();
		const res = await getKnowledgePointsById(route.query.id);
		// 存储不重复的课程参数值
		const uniqueParams = {
			grade: new Set<number>(),
			semester: new Set<number>(),
			stage: new Set<number>(),
			seriesNo: new Set<number>(),
			series: new Set<number>(),
		};

		for (const item of res.data.courseNos) {
			const childRes = await getCourseByNO(item);
			const courseData = childRes.data;
			// 将课程数据添加到Set中（自动去重）
			if (courseData.grade) uniqueParams.grade.add(courseData.grade);
			if (courseData.semester) uniqueParams.semester.add(courseData.semester);
			if (courseData.stage) uniqueParams.stage.add(courseData.stage);
			if (courseData.seriesNo) uniqueParams.seriesNo.add(courseData.seriesNo);
			if (courseData.subject) uniqueParams.series.add(courseData.subject);
		}


		// 将Set转换为数组并赋值给queryParams
		queryParams.grades = Array.from(uniqueParams.grade);
		queryParams.semesters = Array.from(uniqueParams.semester);
		queryParams.stages = Array.from(uniqueParams.stage);
		queryParams.seriesNos = Array.from(uniqueParams.seriesNo);
		queryParams.series = Array.from(uniqueParams.series);
		debugger
		courseNoStrs.value = res.data.courseNoStrs;
		await queryCourseList();
	}
});
</script>

<style lang="scss">
.course {
	// 筛选区域样式优化
	.filter-container {
		padding: 10px 0;

		.filter-item {
			margin: 10px 0;
			overflow: hidden;  // 替代clear:both，更简洁

			.filter-label {
				float: left;
				margin-right: 10px;
				line-height: 32px;  // 与按钮对齐
			}

			.filter-options {
				float: left;
			}
		}
	}

	// 课程内容区域
	.course-content {
		width: 100%;
		margin: 6px 0;
		padding: 10px;
		background: #fbfbfb;
		overflow: hidden;  // 替代float+clear

		// 左侧导航
		.sidebar {
			.tree-container{
				width: 25%;
				float: left;
				border-right: 1px solid #eee;
				padding: 20px;
				height: 300px;
				overflow-y: scroll;
			}

			// 右侧内容
			.content-wrap {
				width: 75%;
				float: left;
				padding: 0 20px;
				height: 320px;

				.filter-bar {
					display: flex;
					justify-content: space-between;
					margin-bottom: 20px;

					.all-tab {
						font-size: 16px;
						color: #007bff;
						border-bottom: 2px solid #007bff;
						padding-bottom: 5px;
					}

					.sort-select {
						padding: 5px 8px;
						border: 1px solid #ddd;
						border-radius: 4px;
					}
				}
			}
			.book-info {
				margin-bottom: 20px;
				cursor: pointer;

				.book-text p {
					font-size: 16px;
					color: #333;
				}
			}
		}


	}
}

// 公共样式
.font14 {
	font-size: 14px;
}
</style>
